All files / src/app/api/admin/monitoring/alerts/[id] route.ts

0% Statements 0/219
100% Branches 0/0
0% Functions 0/1
0% Lines 0/219

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220                                                                                                                                                                                                                                                                                                                                                                                                                                                       
export const dynamic = 'force-dynamic';

import { NextRequest, NextResponse } from 'next/server';
import { prisma } from '@/lib/prisma';
import {
  withAdmin,
  withErrorHandling,
  successResponse,
  errorResponse,
  type ApiSuccessResponse,
  type ApiErrorResponse,
  type AuthenticatedUser,
} from '@/lib/api';
import type { PerformanceAlertConfig, PerformanceAlert } from '@prisma/client';
import type { Session } from 'next-auth';

/**
 * Alert config detail response
 */
interface AlertConfigDetailResponse {
  config: PerformanceAlertConfig & {
    alerts: PerformanceAlert[];
    creator: { id: number; name: string | null; email: string } | null;
  };
  recentAlerts: PerformanceAlert[];
  stats: {
    totalAlerts: number;
    activeAlerts: number;
    acknowledgedAlerts: number;
    resolvedAlerts: number;
  };
}

/**
 * Input for updating an alert config
 */
interface UpdateAlertConfigInput {
  name?: string;
  description?: string;
  metricType?: string;
  scope?: string;
  warningThreshold?: number;
  criticalThreshold?: number;
  evaluationWindow?: number;
  evaluationInterval?: number;
  minSamples?: number;
  notifyOnWarning?: boolean;
  notifyOnCritical?: boolean;
  notificationChannels?: string[];
  cooldownMinutes?: number;
  enabled?: boolean;
}

/**
 * GET /api/admin/monitoring/alerts/[id]
 *
 * Get a single alert configuration with its alerts and stats.
 */
async function handleGet(
  _request: NextRequest,
  context: { params?: Promise<Record<string, string>> } | undefined
): Promise<NextResponse<ApiSuccessResponse<AlertConfigDetailResponse> | ApiErrorResponse>> {
  const params = await context?.params;
  const id = params?.id;

  if (!id) {
    return errorResponse('INVALID_PARAM', 'Alert config ID is required', { status: 400 });
  }

  const config = await prisma.performanceAlertConfig.findUnique({
    where: { id },
    include: {
      alerts: {
        where: { status: 'active' },
        orderBy: { triggeredAt: 'desc' },
        take: 10,
      },
      creator: {
        select: { id: true, name: true, email: true },
      },
    },
  });

  if (!config) {
    return errorResponse('NOT_FOUND', 'Alert configuration not found', { status: 404 });
  }

  // Get recent alerts and stats
  const [recentAlerts, totalAlerts, activeAlerts, acknowledgedAlerts, resolvedAlerts] = await Promise.all([
    prisma.performanceAlert.findMany({
      where: { configId: id },
      orderBy: { triggeredAt: 'desc' },
      take: 50,
    }),
    prisma.performanceAlert.count({ where: { configId: id } }),
    prisma.performanceAlert.count({ where: { configId: id, status: 'active' } }),
    prisma.performanceAlert.count({ where: { configId: id, status: 'acknowledged' } }),
    prisma.performanceAlert.count({ where: { configId: id, status: 'resolved' } }),
  ]);

  return successResponse({
    config,
    recentAlerts,
    stats: {
      totalAlerts,
      activeAlerts,
      acknowledgedAlerts,
      resolvedAlerts,
    },
  });
}

/**
 * PATCH /api/admin/monitoring/alerts/[id]
 *
 * Update an alert configuration.
 */
async function handlePatch(
  request: NextRequest,
  context: { params?: Promise<Record<string, string>> } | undefined,
  // eslint-disable-next-line @typescript-eslint/no-unused-vars
  _session: Session,
  // eslint-disable-next-line @typescript-eslint/no-unused-vars
  _user: AuthenticatedUser
): Promise<NextResponse<ApiSuccessResponse<{ config: PerformanceAlertConfig }> | ApiErrorResponse>> {
  const params = await context?.params;
  const id = params?.id;

  if (!id) {
    return errorResponse('INVALID_PARAM', 'Alert config ID is required', { status: 400 });
  }

  const body = (await request.json()) as UpdateAlertConfigInput;

  // Check if config exists
  const existing = await prisma.performanceAlertConfig.findUnique({
    where: { id },
  });

  if (!existing) {
    return errorResponse('NOT_FOUND', 'Alert configuration not found', { status: 404 });
  }

  // Validate thresholds if both are provided
  const warningThreshold = body.warningThreshold ?? existing.warningThreshold;
  const criticalThreshold = body.criticalThreshold ?? existing.criticalThreshold;

  if (warningThreshold >= criticalThreshold) {
    return errorResponse('VALIDATION_ERROR', 'warningThreshold must be less than criticalThreshold');
  }

  // Validate metricType if provided
  if (body.metricType) {
    const validMetricTypes = ['response_time', 'error_rate', 'throughput', 'p95_latency'];
    if (!validMetricTypes.includes(body.metricType)) {
      return errorResponse('VALIDATION_ERROR', `metricType must be one of: ${validMetricTypes.join(', ')}`);
    }
  }

  const config = await prisma.performanceAlertConfig.update({
    where: { id },
    data: {
      ...(body.name !== undefined && { name: body.name }),
      ...(body.description !== undefined && { description: body.description }),
      ...(body.metricType !== undefined && { metricType: body.metricType }),
      ...(body.scope !== undefined && { scope: body.scope }),
      ...(body.warningThreshold !== undefined && { warningThreshold: body.warningThreshold }),
      ...(body.criticalThreshold !== undefined && { criticalThreshold: body.criticalThreshold }),
      ...(body.evaluationWindow !== undefined && { evaluationWindow: body.evaluationWindow }),
      ...(body.evaluationInterval !== undefined && { evaluationInterval: body.evaluationInterval }),
      ...(body.minSamples !== undefined && { minSamples: body.minSamples }),
      ...(body.notifyOnWarning !== undefined && { notifyOnWarning: body.notifyOnWarning }),
      ...(body.notifyOnCritical !== undefined && { notifyOnCritical: body.notifyOnCritical }),
      ...(body.notificationChannels !== undefined && { notificationChannels: body.notificationChannels }),
      ...(body.cooldownMinutes !== undefined && { cooldownMinutes: body.cooldownMinutes }),
      ...(body.enabled !== undefined && { enabled: body.enabled }),
    },
  });

  return successResponse({ config });
}

/**
 * DELETE /api/admin/monitoring/alerts/[id]
 *
 * Delete an alert configuration and all its alerts.
 */
async function handleDelete(
  _request: NextRequest,
  context: { params?: Promise<Record<string, string>> } | undefined
): Promise<NextResponse<ApiSuccessResponse<{ deleted: boolean }> | ApiErrorResponse>> {
  const params = await context?.params;
  const id = params?.id;

  if (!id) {
    return errorResponse('INVALID_PARAM', 'Alert config ID is required', { status: 400 });
  }

  // Check if config exists
  const existing = await prisma.performanceAlertConfig.findUnique({
    where: { id },
  });

  if (!existing) {
    return errorResponse('NOT_FOUND', 'Alert configuration not found', { status: 404 });
  }

  // Delete config (cascades to alerts due to onDelete: Cascade)
  await prisma.performanceAlertConfig.delete({
    where: { id },
  });

  return successResponse({ deleted: true });
}

// Export handlers with middleware
export const GET = withErrorHandling(withAdmin(handleGet));
export const PATCH = withErrorHandling(withAdmin(handlePatch));
export const DELETE = withErrorHandling(withAdmin(handleDelete));